const crypto = require('crypto');

module.exports = Object.freeze({
	encodeSHA256(raw) {
		return crypto.createHash('sha256').update(String(raw)).digest().toString('hex');
	},
	randomInt(from, to) {
		return Math.round(Math.random() * (to - from) + from);
	},
	salt(length = 8) {
		return Math.random().toString(16).substr(2, length);
	},
	async sleep(delay = 500) {
		return new Promise(resolve => setTimeout(resolve, delay));
	},
	uuid() {
		return crypto.randomUUID({ disableEntropyCache: true }).replace(/-/g, '');
	},
	uuid2() {
		return crypto.randomUUID({ disableEntropyCache: true });
	},
	isFalseValue(val) {
		return val === undefined || val === null || val === '';
	},
	isValidUUID(uuid) {
		const uuidRegex = /^[0-9a-fA-F]{32}$/;

		return uuidRegex.test(uuid);
	},
	// 数组多维化
	convertArray(columns, arr) {
		if (columns === 0) return arr;

		return arr.reduce((result, item, index) => {
			const rowIndex = Math.floor(index / columns);
			const colIndex = index % columns;

			if (!result[rowIndex]) {
				result[rowIndex] = [];
			}

			result[rowIndex][colIndex] = item;

			return result;
		}, []);
	},
	handleResponse(code, msg, data = null) {
		return {
			code,
			msg,
			data
		};
	},
	intersection(arr1, arr2) {
		return arr1.filter((val) => arr2.indexOf(val) > -1);
	},
	isDoubleDimensional(array) {
		return Array.isArray(array)
			? array.every(item => Array.isArray(item))
			: false;
	},
	// 弧度转角度
	radians2degress(radians) {
		return radians * (180 / Math.PI);
	},
	// 角度转弧度
	degress2radians(degrees) {
		return degrees * (Math.PI / 180);
	}
});